﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EGEHaina.Models;
using EGEHaina.Areas.Contract.Models;
using EGEHaina.Library.Controllers;
using EGEHaina.Library.Session;

namespace EGEHaina.Areas.Contract.Controllers
{
    public class ContractController : BaseController
    {
        private EGEHainaContext db = new EGEHainaContext();
        //
        // GET: /Contract/Manage/

        public ActionResult Index()
        {
            return RedirectToAction("Read");
        }

        public ActionResult Read()
        {
            db.Contracts.ToList();
            return View();
        }

        public ActionResult Create()
        {
            ViewBag.ContractTypes = new SelectList(db.ContractTypes, "ContractTypeId", "Name");
            ViewBag.Departments = new SelectList(db.Departments, "DepartmentId", "Name");
            return View();
        }

        public ActionResult CreateSave(EGEHaina.Areas.Contract.Models.Contract model)
        {
            //verificamos si los datos son validos
            if (ModelState.IsValid)
            {
                db.Contracts.Add(model);
                db.SaveChanges();
                FlashMessage("Your entry was successfully saved." + model.ContractId, FlashMessenger.MessageType.Success);
                return Redirect("Read");
            }
            else
            {
                // sacamos todos lo errores ocurridos en el modelo
                var errors = ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage).ToList();
                foreach (var error in errors)
                {
                    FlashMessage(error, FlashMessenger.MessageType.Error);
                }
                return Redirect("Create");
            }
        }

        /// <summary>
        /// Carga un formulario con los datos del modelo
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Update(int id)
        {
            EGEHaina.Areas.Contract.Models.Contract contract = db.Contracts.Find(id);
            return View(contract);
        }

    }
}
